#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    ui->send_button->setEnabled(false);

    socket = new QWebSocket("QWebsocket", QWebSocketProtocol::VersionLatest, this);
    connect(socket, &QWebSocket::connected, this, &MainWindow::connected);
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(disconnected));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));

    connect(socket, &QWebSocket::textMessageReceived, this, &MainWindow::recvData);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_connect_pushButton_clicked()
{
    if(ui->ip_linEdit->text().isNull() || ui->port_lineEdit->text().isNull())
        return ;

    QString ip = ui->ip_linEdit->text();
    int port = ui->port_lineEdit->text().toInt();

    QString url = QString("ws://%1:%2").arg(ip).arg(port);
    socket->abort();
    socket->open(QUrl(url));
}


void MainWindow::recvData(const QString &data)
{
    qDebug() << data;
    ui->recv_lineEdit->setText(data);
}

void MainWindow::on_send_button_clicked()
{
    QString data = ui->send_lineEdit->text();
    if(data.isEmpty())
        return ;

    socket->sendTextMessage(data);
}

void MainWindow::disconnected()
{
    socket->abort();
    ui->connect_pushButton->setEnabled(true);
    ui->send_button->setEnabled(false);
}

void MainWindow::connected()
{
    qDebug() << "connect";
    ui->send_button->setEnabled(true);
}









